﻿using Microsoft.Web.WebView2.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MDReader.Control
{
    public partial class CtrlBrowser : UserControl
    {
        public CtrlBrowser()
        {
            InitializeComponent();

        }

        #region 专用属性
        public event EventHandler? InitalizedAfter;

        class LastSearchItem
        {
            public string SearchText { get; set; } = "";
            public int Index { get; set; } = -1;
        }
        private LastSearchItem LastSearch = new LastSearchItem();

        public event EventHandler<CoreWebView2WebMessageReceivedEventArgs>? ReceivedAfter;
        #endregion

        #region 专用方法
        private async void Search()
        {
            try
            {
                if (LastSearch.SearchText != txtFind.Text)
                {
                    //int Index = rtbContent.Find(txtFind.Text);
                    //rtbContent.Select(Index, txtFind.Text.Length);
                    //LastSearch.Index = Index;
                    string script = $@"
            (function() {{
                var searchText = '{txtFind.Text}';
                var bodyText = document.body.innerText;
                var index = bodyText.indexOf(searchText);
                if (index !== -1) {{
                    var range = document.createRange();
                    var selection = window.getSelection();
                    selection.removeAllRanges();
                    var startNode = document.body;
                    var endNode = document.body;
                    var startOffset = index;
                    var endOffset = index + searchText.length;
                    range.setStart(startNode, startOffset);
                    range.setEnd(endNode, endOffset);
                    selection.addRange(range);
                }}
                return index;
            }})();
        ";
                    var result = await wvContent.CoreWebView2.ExecuteScriptAsync(script);
                    int Index = -1;
                    try { int.TryParse(result, out Index); } catch { }
                    LastSearch.Index = Index;
                    //if (result == "true")
                    //{
                    //    MessageBox.Show("Text found and highlighted.");
                    //}
                    //else
                    //{
                    //    MessageBox.Show("Text not found.");
                    //}
                }
                else
                {
                    //int LastIndex = LastSearch.Index + txtFind.Text.Length;
                    //if (LastSearch.Index < 0)
                    //    LastIndex = 0;
                    //int Index = rtbContent.Find(txtFind.Text, LastIndex, RichTextBoxFinds.None);
                    //rtbContent.Select(Index, txtFind.Text.Length);
                    //if (Index >= 0)
                    //    LastSearch.Index = Index;
                    int LastIndex = LastSearch.Index + txtFind.Text.Length;
                    if (LastSearch.Index < 0)
                        LastIndex = 0;
                    string script = $@"
            (function() {{
                var searchText = '{txtFind.Text}';
                var bodyText = document.body.innerText;
                var index = bodyText.indexOf(searchText, {LastIndex});
                if (index !== -1) {{
                    var range = document.createRange();
                    var selection = window.getSelection();
                    selection.removeAllRanges();
                    var startNode = document.body;
                    var endNode = document.body;
                    var startOffset = index;
                    var endOffset = index + searchText.length;
                    range.setStart(startNode, startOffset);
                    range.setEnd(endNode, endOffset);
                    selection.addRange(range);
                }}
                return index;
            }})();
        ";
                    var result = await wvContent.CoreWebView2.ExecuteScriptAsync(script);
                    int Index = -1;
                    try { int.TryParse(result, out Index); } catch { }
                    if (Index >= 0)
                        LastSearch.Index = Index;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查找时遇到问题: {ex.Message}");
            }
            LastSearch.SearchText = txtFind.Text;
        }

        public void JumpTo(string Id)
        {
            // 跳转到对应位置
            if (wvContent.CoreWebView2 != null)
                wvContent.CoreWebView2.ExecuteScriptAsync($"document.getElementById('{Id}').scrollIntoView();");
        }
        public void NavigateTo(string htmlText)
        {
            wvContent.NavigateToString(htmlText);
        }
        public async void ClearContent()
        {
            if (wvContent.CoreWebView2 != null)
                await wvContent.CoreWebView2.ExecuteScriptAsync("document.body.innerHTML = '';");
        }
        public void ShowFind()
        {
            pnlFind.Visible = true;
            txtFind.Focus();
        }

        #endregion

        #region 事件处理
        private void frmBrowser_Load(object sender, EventArgs e)
        {

            Task T = wvContent.EnsureCoreWebView2Async(null);
            wvContent.CoreWebView2InitializationCompleted += (s, a) =>
            {
                if (InitalizedAfter != null)
                    InitalizedAfter(this, new EventArgs());
            };
        }
        private void btnCloseFind_Click(object sender, EventArgs e)
        {
            pnlFind.Visible = false;
        }

        private void txtFind_KeyDown(object sender, KeyEventArgs e)
        {
            if (e == null)
                return;
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    {
                        Search();
                    }
                    break;
                case Keys.Escape:
                    btnCloseFind_Click(sender, e);
                    break;
            }
        }

        private void WvContent_NavigationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
        {
            // 为每个标题添加ID
            wvContent.CoreWebView2.ExecuteScriptAsync(@"
            document.querySelectorAll('h1, h2, h3, h4, h5, h6').forEach((heading, index) => {
                heading.id = 'heading-' + index;
            });
        ");
        }

        private void WebView_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
        {
            if(ReceivedAfter!=null)
                ReceivedAfter(this, e);
        }
        #endregion
    }
}
